<template>
  <div class="app-container">
    <div class="filter-container">
      <!--<el-select v-model="listQuery.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 200px;margin-right: 20px">
        <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>-->
      <el-input
        v-model="listQuery.wNickname"
        :placeholder="'请输入外观名称或昵称'"
        style="width: 200px;margin-right: 20px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.wType" placeholder="可选择外观类型" class="filter-item">
        <el-option
          v-for="item in typeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh" @click="clearFilter">
        刷新
      </el-button>
      <el-button
        v-has="'jiansanObjList:add'"
        v-waves
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        {{ $t('table.add') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="'图片'" show-overflow-tooltip width="100px">
        <template slot-scope="scope">
          <template v-if="!!picUrl+'news/'+scope.row.wId+'.jpg'">
            <el-popover
              placement="top-start"
              trigger="hover"
            >
              <span>
                <img :src="picUrl+'news/'+scope.row.wId+'.jpg'" alt="" style="width: 200px;height: 200px">
              </span>
              <span slot="reference">
                <img :src="picUrl+'news/'+scope.row.wId+'.jpg'" alt="" style="width: 50px;height: 50px">
              </span>
            </el-popover>
          </template>
        </template>
      </el-table-column>

      <el-table-column :label="tempDesc.wId">
        <template slot-scope="scope">
          <span>{{ scope.row.wId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.wType">
        <template slot-scope="scope">
          <span>{{ scope.row.wType }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.wName">
        <template slot-scope="scope">
          <span>{{ scope.row.wName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.wNickname">
        <template slot-scope="scope">
          <span>{{ scope.row.wNickname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.wTimeornum">
        <template slot-scope="scope">
          <span>{{ scope.row.wTimeornum }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.wPublishTime" width="160px">
        <template slot-scope="scope">
          <span>{{ scope.row.wPublishTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.uTime" width="160px">
        <template slot-scope="scope">
          <span>{{ scope.row.uTime | formatDate }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="checkBtnPermission(['jiansanObjList:edit','jiansanObjList:delete','jiansanObjList:toprice'])" :label="$t('table.actions')" width="450px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-has="'jiansanObjList:edit'" type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button v-has="'jiansanObjList:delete'" type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">
            {{ $t('table.delete') }}
          </el-button>
          <el-button v-has="'jiansanObjList:toprice'" type="primary" size="mini" @click="handleToPrices(scope.row)">
            所有价格
          </el-button>
          <el-button v-has="'jiansanObjList:addprice'" type="primary" size="mini" @click="handleAddPrice(scope.row)">
            新增价格
          </el-button>
          <el-button v-has="'jiansanObjList:toBaojia'" type="primary" size="mini" @click="handleToBaojia(scope.row)">
            所有报价
          </el-button>
          <el-button v-has="'jiansanObjList:addBaojia'" type="primary" size="mini" @click="handleAddBaojia(scope.row)">
            新增报价
          </el-button>
<!--          <el-button v-has="'jiansanObjList:addprice'" type="primary" size="mini">-->
<!--            <el-upload-->
<!--              :before-upload="beforeUpload"-->
<!--              accept="image/jpeg,image/jpg,image/gif,image/png"-->
<!--              :headers="headers"-->
<!--              :action="uploadUrl"-->
<!--              :data="{wId:scope.row.wId}"-->
<!--              :on-success="handleImageSuccess"-->
<!--            >-->
<!--              点击上传-->

<!--            </el-upload>-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item :label="tempDesc.wType" prop="wType">
          <el-select v-model="temp.wType" placeholder="请选择" size="medium">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.wName" prop="wName">
          <el-input v-model="temp.wName" :placeholder="'请输入' + tempDesc.wName" />
        </el-form-item>
        <el-form-item :label="tempDesc.wNickname" prop="wNickname">
          <el-input v-model="temp.wNickname" :placeholder="'请输入' + tempDesc.wNickname" />
        </el-form-item>
        <el-form-item :label="tempDesc.wPublishTime" prop="wPublishTime">
          <el-input v-model="temp.wPublishTime" :placeholder="'请输入' + tempDesc.wPublishTime" />
        </el-form-item>
        <el-form-item :label="tempDesc.wTimeornum" prop="wTimeornum">
          <el-input v-model="temp.wTimeornum" :placeholder="'请输入' + tempDesc.wTimeornum" />
        </el-form-item>
        <el-form-item :label="tempDesc.wPic" prop="wPic">
          <el-input v-model="temp.wPic" :placeholder="'请输入' + tempDesc.wPic" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="'新增价格'" :visible.sync="dialogFormVisiblePrice">
      <el-form
        ref="dataFormPrice"
        :rules="rules"
        :model="tempPrice"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <!--<el-form-item :label="tempDesc.wxAccountId" prop="wxAccountId">
          <el-select v-model="temp.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 280px;" :disabled="dialogStatus !='create'">
            <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>-->
        <el-form-item :label="'外观官方名称'" prop="wName">
          <el-input v-model="tempPrice.wName" disabled="true" />
        </el-form-item>
        <el-form-item :label="'外观昵称'" prop="wNickname">
          <el-input v-model="tempPrice.wNickname" disabled="true" />
        </el-form-item>
        <el-form-item :label="'时间'" prop="wDate">
          <el-input v-model="tempPrice.wDate" :placeholder="'请输入时间'" />
        </el-form-item>
        <el-form-item :label="'电五价格'" prop="wPriceDxw">
          <el-input v-model="tempPrice.wPriceDxw" :placeholder="'请输入电五价格'" />
        </el-form-item>
        <el-form-item :label="'网通价格'" prop="wPriceWty">
          <el-input v-model="tempPrice.wPriceWty" :placeholder="'请输入网通价格'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisiblePrice = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="addPrice()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>import { getToken } from '@/utils/auth'
import { checkBtnPermission } from '@/utils/permission' // 权限判断函数
import { fetchList, createRow, updateRow, deleteRow, addPriceApi } from '@/api/w-obj'
import { fetchAllAccount } from '@/api/wx-account'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

// 常量title
const tempDesc = {
  'wId': '主键',
  'wType': '外观类型',
  'wName': '外观官方名称',
  'wNickname': '外观昵称',
  'wPublishTime': '外观上架时间',
  'iTime': '系统录入时间',
  'uTime': '系统修改时间',
  'wTimeornum': '外观限制',
  'wPic': '外观图片'
}
export default {
  // name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    formatDate(date, fmt) {
      if (!date) {
        return
      }
      date = new Date(date)
      if (typeof (fmt) === 'undefined') {
        fmt = 'yyyy-MM-dd HH:mm:ss'
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'H+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      }
      for (const k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          const str = o[k] + ''
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length))
        }
      }
      return fmt
    }
  },
  data() {
    return {
      headers: { 'X-Token': getToken() },
      uploadUrl: process.env.BASE_API + '/api/upload/addImgWithId',
      picUrl: process.env.PIC_URL,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        wNickname: ''
      },
      wName: '',
      temp: {
        'wId': '',
        'wType': '',
        'wName': '',
        'wNickname': '',
        'wPublishTime': '',
        'iTime': '',
        'uTime': '',
        'wTimeornum': '',
        'wPic': ''
      },
      tempPrice: {
        'wName': '',
        'wNickname': '',
        'wPid': '',
        'wObjid': '',
        'wDate': '',
        'wPriceDxw': '',
        'wPriceWty': ''
      },
      tempDesc: tempDesc,
      dialogFormVisible: false,
      dialogFormVisiblePrice: false,
      dialogStatus: '',
      dialogStatusPrice: '',
      textMap: {
        update: '编辑',
        create: '增加'
      },
      rules: {
        wType: [{ required: true, message: '请输入' + tempDesc.wType, trigger: 'blur' }],
        wName: [{ required: true, message: '请输入' + tempDesc.wName, trigger: 'blur' }],
        wNickname: [{ required: true, message: '请输入' + tempDesc.wNickname, trigger: 'blur' }],
        wPublishTime: [{ pattern: /\d{4}-\d{2}-\d{2}/, message: '请输入正确的日期格式,如2019-01-01', trigger: 'blur' },
          { required: true, message: '请输入' + tempDesc.wPublishTime, trigger: 'blur' }]
      },
      accountListOptions: [
      ],
      fansOptions: [],
      loading: false,
      fansSelected: [],
      typeOptions: [{
        value: '红发',
        label: '红发'
      }, {
        value: '金发',
        label: '金发'
      }, {
        value: '礼盒',
        label: '礼盒'
      }, {
        value: '披风',
        label: '披风'
      }, {
        value: '小玩意',
        label: '小玩意'
      }]
    }
  },
  created() {
    this.getList()
    this.getAccountList()
  },
  methods: {
    checkBtnPermission,
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    clearFilter() {
      this.listQuery.wType = ''
      this.listQuery.wNickname = ''
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        'wId': '',
        'wType': '',
        'wName': '',
        'wNickname': '',
        'wPublishTime': '',
        'iTime': new Date(),
        'uTime': new Date(),
        'wTimeornum': '',
        'wPic': ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createRow(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleAddPrice(row) {
      this.tempPrice.wObjid = row.wId
      this.tempPrice.wName = row.wName
      this.tempPrice.wNickname = row.wNickname
      this.dialogFormVisiblePrice = true
      this.$nextTick(() => {
        this.$refs['dataFormPrice'].clearValidate()
      })
    },
    addPrice() {
      this.$refs['dataFormPrice'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempPrice)
          addPriceApi(tempData).then(() => {
            this.dialogFormVisiblePrice = false
            this.$notify({
              title: '成功',
              message: '新增价格成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.uTime = new Date()
          const tempData = Object.assign({}, this.temp)
          updateRow(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleToPrices(row) {
    //  this.wName = row.wName//  next({ path: '/401', replace: true, query: { noGoBack: true }})
      this.$router.push({ name: 'cc', params: { id: row.wName }})
    },
    handleToBaojia(row) {
      //  this.wName = row.wName//  next({ path: '/401', replace: true, query: { noGoBack: true }})
      this.$router.push({ name: 'ee', params: { id: row.wName }})
    },
    handleDelete(row) {
      if (row.isRelatedMenu === '1') {
        this.$message({ message: '请先解除关联', type: 'warning' })
        return false
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var params = { 'id': parseInt(row.wId) }
          deleteRow(params).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
    },
    getAccountList() {
      fetchAllAccount().then(response => {
        this.accountListOptions = []
        for (var i = 0; i < response.data.length; i++) {
          this.accountListOptions.push({ 'key': response.data[i].id + '', 'display_name': response.data[i].name })
        }
      })
    },
    beforeUpload(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/jpg' || 'image/gif' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.success('上传文件大小不能超过 2MB!')
      }
    },
    handleImageSuccess(res) {
      if (res.code === 200) {
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>
